package quangtqServlet;

import java.io.*;
import java.util.Iterator;
import java.util.List;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

@WebServlet(name="CommonsFileUploadServlet", urlPatterns={"/CommonsFileUploadServlet"})
public class CommonsFileUploadServlet extends HttpServlet {

    private static final String TMP_DIR_PATH = "c:\\tmp";
    private File tmpDir;
    private static String DESTINATION_DIR_PATH = "/files";
    private File destinationDir;

    @Override
    public void init(ServletConfig config) throws ServletException
    {
        super.init(config);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
    {
        DESTINATION_DIR_PATH = "/files";
        String dirName = "/" + (String)request.getSession().getAttribute("MailID");
        String strDirectoy = getServletContext().getRealPath(DESTINATION_DIR_PATH + dirName);
        boolean success = (new File(strDirectoy)).mkdir();
        if(success)
        {
            System.out.println("Directory: " + strDirectoy + " created");
            DESTINATION_DIR_PATH += dirName;
        }

        tmpDir = new File(TMP_DIR_PATH);
        if (!tmpDir.isDirectory())
        {
            throw new ServletException(TMP_DIR_PATH + " is not a directory");
        }

        String realPath = getServletContext().getRealPath(DESTINATION_DIR_PATH);
        destinationDir = new File(realPath);
        if (!destinationDir.isDirectory())
        {
            throw new ServletException(DESTINATION_DIR_PATH + " is not a directory");
        }

        PrintWriter out = response.getWriter();
        response.setContentType("text/plain");
        out.println("<h1>Servlet File Upload Example using Commons File Upload</h1>");
        out.println(getServletContext().getRealPath(DESTINATION_DIR_PATH));
        out.println();

        DiskFileItemFactory fileItemFactory = new DiskFileItemFactory();

        //Set the size threshold, above which content will be stored on disk.
        fileItemFactory.setSizeThreshold(100 * 1024 * 1024); //1 MB

         // Set the temporary directory to store the uploaded files of size above threshold.
        fileItemFactory.setRepository(tmpDir);

        ServletFileUpload uploadHandler = new ServletFileUpload(fileItemFactory);
        try
        {
            // Parse the request
            List items = uploadHandler.parseRequest(request);
            Iterator itr = items.iterator();
            while (itr.hasNext())
            {
                FileItem item = (FileItem) itr.next();

                // Handle Form Fields.
                if (item.isFormField())
                {
                    out.println("File Name = " + item.getFieldName() + ", Value = " + item.getString());
                }
                else
                {
                    //Handle Uploaded files.
                    out.println("Field Name = " + item.getFieldName()
                            + ", File Name = " + item.getName()
                            + ", Content type = " + item.getContentType()
                            + ", File Size = " + item.getSize());

                     // Write file to the ultimate location.
                    if(!item.getName().equals(""))
                    {
                        File file = new File(destinationDir, item.getName());
                        item.write(file);
                    }
                }
//                out.close();
            }

            DESTINATION_DIR_PATH = "/files";
            response.sendRedirect("sendMailSuccess.jsp");
        }
        catch (FileUploadException ex)
        {
            System.out.print(ex.getMessage());
        }
        catch (Exception ex)
        {
            System.out.print(ex.getMessage());
        }

    }
}
